//
//  ZCinformationVC.m
//  zctx
//
//  Created by apple on 16/1/5.
//  Copyright © 2016年 sanliang. All rights reserved.
//

#import "ZCinformationVC.h"
#import "ActionView.h"
#import "ZCLoginVC.h"
#import "ZCCommentVC.h"
#import "iToastImage.h"
#import "HcCustomKeyboard.h"

#import "ZCInvolvedNewcommentsCell.h"
#import "ZCInvolvedcommentsCell.h"
#import "ZCinvolvedOtherCell.h"

#import "ZCCommentDetailsVC.h"
#import "SXHTTPManager.h"


@interface ZCinformationVC ()<UIWebViewDelegate,UITableViewDataSource,UITableViewDelegate,ZCinvolvedOtherCellDelegate,HcCustomKeyboardDelegate,ZCInvolvedNewcommentsCellDelegate>


@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong)UIButton *rightButton;
@property (nonatomic,strong)UIButton *commentButton;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)ZCInvolvedToolView *toolView;

@property (nonatomic,assign)float scale;
@property (nonatomic,assign)NSInteger ifcollection;
@property (nonatomic,strong)NSDictionary *dataDict;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic) BOOL ishas; //web有数据
@property (nonatomic) BOOL iscomment; //是否滚动到评论



@end

@implementation ZCinformationVC
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCinformationVC"];
    [MTA trackPageViewBegin:@"ZCinformationVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCinformationVC"];
    [MTA trackPageViewEnd:@"ZCinformationVC"];
}

-(void)updateRequest{
    if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus >0) {
        self.bannerView.hidden = YES;
    }
    [self loadData];
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.iscomment = YES;//是滚动到评论
    self.ishas = NO;
    self.scale = 1.0;
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataDict = [NSDictionary dictionary];
    [self initnavegation];
    [self.view addSubview:self.tableView];
    [self initFooterView];

    
    [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadData];
    });
}

#pragma mark FooterView
-(void)initFooterView{
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"ZCInvolvedToolView" owner:self options:nil];
    //得到第一个UIView
    self.toolView = [nib objectAtIndex:0];
    self.toolView.hidden = YES;
    [self.view addSubview:self.toolView];
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.height.mas_equalTo(44);
        make.width.mas_equalTo(@(SCREEN_WIDTH));
        make.top.equalTo(self.tableView.bottom).with.offset(0);
    }];
 
    __weak ZCinformationVC *weakSelf = self;
    self.toolView.TshareBlock = ^(void){
        [weakSelf shareButtonPressed:nil];
    };
    self.toolView.TcollectBlock = ^(void){
        [weakSelf collectionButtonPressed];
    };
    self.toolView.TcommentBlock = ^(void){
        NSIndexPath *scrollIndexPath;
        if(weakSelf.iscomment ==YES){
            scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
            [weakSelf.tableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }else{
            [weakSelf.tableView setContentOffset:CGPointMake(0,-64) animated:YES];
        }
        weakSelf.iscomment = !weakSelf.iscomment;
    };
    self.toolView.TtextfiledBlock = ^(void){
        [weakSelf ClickCommentButtonconnect];
    };
}

#pragma mark 请求热点资讯评论
-(void)initNewsData{
    NSString *strtype = nil;
    if ([self.isweekly isEqualToString:@"1"]) {
        strtype = @"6";
    }else{
        strtype = @"2";
    }
    [NetworkManager requestIndexnewsgetoneWithNewid:self.urlID mid:UserModel.mid password:UserModel.password ctype:strtype success:^(NSDictionary *dictResponse) {
        NSObject *dataRR  = (NSObject *)[dictResponse objectForKey:@"content"];
        if ([dataRR isKindOfClass:[NSDictionary class]]){
            NSDictionary *dict = (NSDictionary *)dataRR;
            self.dataDict = [dict copy];
            self.toolView.ModelDic = [dict copy];

            NSObject *hot_array =(NSObject *)[dict objectForKey:@"hot_comments"];
            if ([hot_array isKindOfClass:[NSArray class]]) {
                NSArray *array  = (NSArray *)hot_array;
                if (array.count>0) {
                    for (NSDictionary *dict in array) {
                        ZCInvolvedDetailsModelHotComments *model = [ZCInvolvedDetailsModelHotComments modelObjectWithDictionary:dict];
                        [self.dataArray addObject:model];
                    }
                }
            }
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
    
   UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 24, 22);
    [rightButton addTarget:self action:@selector(shareButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_rightNavBar = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [rightButton setImage:[UIImage imageNamed:@"Involved_tshare"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = barButtonItem_rightNavBar;
    
}

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadData{
    
    NSString *strurls = [NSString stringWithFormat:@"%@/index.php/Api/V2/Index/get_htmlencode_by_type?id=%@",[NetworkManager strURLBasic],self.urlID];
    
    NSLog(@"self.strURL = %@",strurls);
    
    [[SXHTTPManager manager] GET:strurls parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = (NSDictionary *)responseObject;
            
            NSDictionary *dci = [dict objectForKey:@"content"];
            NSString *str = [dci objectForKey:@"content"];
            
            NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]};
            
            NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[NSData dataWithData:[str dataUsingEncoding:NSUTF8StringEncoding]] options:options documentAttributes:nil error:nil];
            
            NSString *resplacString = [NSString stringWithFormat:@"%@%@",@"src=\"",[NetworkManager strURLBasic]];
//            NSLog(@"resplacString = %@",resplacString);
            NSString *strHtml = [attrStr.string stringByReplacingCharactersInRangeString:attrStr.string andString:@"src=\"" andorString:resplacString];
            
            int timeInt =[[dci objectForKey:@"ctime"] intValue];
            NSString *time = [NSString stringWithFormat:@"%@ %@",[dci objectForKey:@"author"],dateTimeWithNStringGG(timeInt)];
            
            NSMutableString *body = [NSMutableString string];
            [body appendFormat:@"<div class=\"title\">%@</div>",[dci objectForKey:@"title"]];
            [body appendFormat:@"<div class=\"time\">%@</div>",time];
//            [body appendFormat:@"<div class=\"ss\"><hr></div>"];
            
            [body appendString:strHtml];
            
            [self showInWebView:body];
            
            [self initNewsData];//热点资讯
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [GMDCircleLoader hideFromView:self.view animated:YES];
        self.bannerView.hidden = NO;
    }];
}

#pragma mark - ******************** 拼接html语言
- (void)showInWebView:(NSString *)toBody
{
    NSMutableString *html = [NSMutableString string];
    [html appendString:@"<html>"];
    [html appendString:@"<head>"];
    [html appendString:@"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no\">"];
   [html appendString:@"<meta name=\"renderer\" content=\"webkit\">"];
    [html appendFormat:@"<link rel=\"stylesheet\" href=\"%@\">",[[NSBundle mainBundle] URLForResource:@"SXDetails.css" withExtension:nil]];
    [html appendString:@"<style>"];
    [html appendString:@"img{width:100%;}"];
    [html appendString:@"</style>"];
    [html appendString:@"</head>"];
    [html appendString:@"<body style=\"background:#ffffff;font-size:16px;padding:15;margin:0;\">"];
    [html appendString:toBody];
    [html appendString:@"</body>"];
    [html appendString:@"</html>"];
    [self.webView loadHTMLString:html baseURL:nil];
}


#pragma mark webViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    self.ishas = YES;
    [GMDCircleLoader hideFromView:self.view animated:YES];
    self.bannerView.hidden = YES;
    
    if (webView.isLoading) {
        return;
    }
    
//    CGFloat heightWeb = self.webView.scrollView.contentSize.height;
//    CGRect frame = self.webView.frame;
//    frame.size.height = heightWeb;
//    self.webView.frame = frame;
    
//    CGRect frame = self.webView.frame;
//    frame.size.height = 1;
//    self.webView.frame = frame;
//    CGSize fittingSize = [self.webView sizeThatFits:CGSizeZero];
//    frame.size = fittingSize;
//    self.webView.frame = frame;
//    
    
    
    CGFloat webViewHeight =[[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue];
    
    // CGFloat webViewHeight= [[webViewstringByEvaluatingJavaScriptFromString:@document.body.scrollHeight]floatValue];
    
    CGRect newFrame = webView.frame;
    
    newFrame.size.height= webViewHeight;
    
    webView.frame= newFrame;
    
    self.tableView.hidden = NO;
    [self.tableView reloadData];
    self.toolView.hidden = NO;
    
    NSLog(@"加载完成了--- %f",webViewHeight);
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [GMDCircleLoader hideFromView:self.view animated:YES];
    self.bannerView.hidden = NO;
}

#pragma mark TableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return self.webView;
    }else{
        return nil;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section ==0) {
        return nil;
    }else{
        UIView *footer = [[UIView alloc]init];
        if (self.dataArray.count>=10) {
            NSString *coment_count  = [NSString stringWithFormat:@"%@",[self.dataDict objectForKey:@"comment_count"]];
            NSString *commentStr = [NSString stringWithFormat:@"查看更多评论(%@)>",coment_count];
            UIButton *commentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
            commentButton.titleLabel.font = [UIFont systemFontOfSize:15];
            commentButton.backgroundColor = [UIColor whiteColor];
            [commentButton setTitle:commentStr forState:UIControlStateNormal];
            [commentButton setTitleColor:MainColor forState:UIControlStateNormal];
            [commentButton addTarget:self action:@selector(morecommentInfo) forControlEvents:UIControlEventTouchUpInside];
            return commentButton;
        }else if(self.dataArray.count==0){
            footer.backgroundColor = [UIColor whiteColor];
            UILabel *fnocomment = [[UILabel alloc]init];
            [footer addSubview:fnocomment];
            [fnocomment makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(footer.centerY).with.offset(0);
                make.centerX.equalTo(footer.centerX).with.offset(0);
                make.height.mas_equalTo(21);
                make.width.mas_equalTo (SCREEN_WIDTH);
            }];
            
            fnocomment.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
            fnocomment.font = [UIFont systemFontOfSize:15];
            fnocomment.text = @"暂无评论,我来说两句";
            fnocomment.textAlignment = NSTextAlignmentCenter;
            return footer;
        }else{
            return footer;
        }
    }
}

- (CGFloat )tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return self.webView.frame.size.height;
    }else{
        return 0.001;
    }
}

- (CGFloat )tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section==0) {
        return 0.001;
    }else{
        if (self.dataArray.count>=10 || self.dataArray.count==0) {
            return 64;
        }else{
            return 0.0001;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return 0;
    }else{
        if (self.ishas == YES) {
            return 1 + self.dataArray.count;
        }else{
            return 0;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row>0) {
        [self commentButtonClickindex:indexPath];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        static NSString *IDcell = @"goodcommentCell";
        ZCinvolvedOtherCell *cell = [tableView dequeueReusableCellWithIdentifier:IDcell];
        if (!cell) {
            cell = [[ZCinvolvedOtherCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:IDcell cellType:ZCinvolvedOtherCellTypetitle];
        }
        cell.delegate = self;
        cell.labelTitle.text = @"精彩评论";
        return cell;
    }else{
        static NSString *IDcell = @"commemtsasdCell";
        ZCInvolvedNewcommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:IDcell];
        if (!cell) {
            cell = [[ZCInvolvedNewcommentsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:IDcell];
        }
        cell.delegate = self;
        if (self.dataArray.count>0) {
            [cell setFriendModel:self.dataArray[indexPath.row-1]];
        }
        cell.indexPath = indexPath;
        cell.tableView = tableView;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        return 44;
    }else{
        return [UITableViewCell whc_CellHeightForIndexPath:indexPath tableView:tableView];
    }
    
    return CGFLOAT_MIN;
}


#pragma mark 查看更多评论
-(void)morecommentInfo{
    // *** 将UI操作放到主线程中执行 ***
    ZCCommentVC *comment = [[ZCCommentVC alloc]init];
    comment.pid = self.urlID;
    comment.isarticle  = 1;
    comment.isweekly = self.isweekly;
    comment.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:comment animated:YES];
    
}
#pragma mark 分享点击
-(void)shareButtonPressed:(id *)button{
    ActionView *action = [[ActionView alloc]initWithFrame:CGRectZero];
    action.pid = self.urlID;
    if ([self.isweekly isEqualToString:@"1"]) {
        action.isweb =2;
    }else{
        action.isweb =1;
    }
    [action showInView:self.view];
}

#pragma  mark 收藏
-(void)collectionButtonPressed{
    if (UserModel.password.length>1) {
        NSString *ctype = nil;
        if ([self.isweekly isEqualToString:@"1"]) {
            ctype = @"6";
        }else{
            ctype = @"2";
        }
        if (self.ifcollection == 0) { //收藏
            [NetworkManager requestIndexGetAddarticleCollectionWithNewsid:self.urlID mid:UserModel.mid password:UserModel.password ifcollection:@"1" ctype:ctype success:^(NSDictionary *dictResponse) {
                self.ifcollection = 1;
                [[iToastImage makeinit]showImg:[UIImage imageNamed:@"projectdetail_collection_success"]];
                [self.toolView.collectBtn setImage:[UIImage imageNamed:@"involve_tool_xing_yes"] forState:UIControlStateNormal];
            } failure:^(NSError *error) {
                
            }];
        }else{
            NSLog(@"取消");
            //取消收藏
            [NetworkManager requestIndexGetAddarticleCollectionWithNewsid:self.urlID mid:UserModel.mid password:UserModel.password ifcollection:@"0" ctype:ctype success:^(NSDictionary *dictResponse) {
                self.ifcollection = 0 ;
                [[iToastImage makeinit]showImg:[UIImage imageNamed:@"projectdetail_collection_fail"]];
                [self.toolView.collectBtn setImage:[UIImage imageNamed:@"involve_tool_xing_no"] forState:UIControlStateNormal];
            } failure:^(NSError *error) {
                
            }];
        }
    }else{
        [self login];
    }
}

#pragma mark 点击我想说两句
-(void)ClickCommentButtonconnect{
    if (UserModel.password.length>1) {
        [[HcCustomKeyboard customKeyboard]textViewShowView:self customKeyboardDelegate:self andType:HcCustomKeyboardTypeBtton andplaceholder:@"我来说两句"];
    }else{
        ZCLoginVC *loginVC = [[ZCLoginVC alloc]init];
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
#pragma mark textView 内容
-(void)talkBtnClick:(UITextView *)textViewGet
{
    NSString *ctype = nil;
    if ([self.isweekly isEqualToString:@"1"]) {
        ctype = @"6";
    }else{
        ctype = @"0";
    }
    [NetworkManager requestIndexGetAddarticleWithNewsid:self.urlID mid:UserModel.mid password:UserModel.password content:textViewGet.text  pid:@"0" ctype:ctype success:^(NSDictionary *dictResponse) {
        NSString *err = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
        NSString *content =[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"content"]];
        if ([err isEqualToString:@"0"]) {
            [[[iToast makeText:@"评论成功"]setGravity:iToastGravityCenter] show];
            ZCInvolvedDetailsModelHotComments *hotcom = [[ZCInvolvedDetailsModelHotComments alloc]init];
            hotcom.avatar = UserModel.avatar;
            hotcom.ctime =[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];;
            hotcom.content = textViewGet.text;
            hotcom.likecount = @"0";
            hotcom.commentCount = @"0";
            hotcom.username = UserModel.username;
            hotcom.hotCommentsIdentifier = content;
            hotcom.forId = self.urlID;
            hotcom.pid =content;
            hotcom.ctype = @"1";
            [self.dataArray insertObject:hotcom atIndex:0];
            [self.tableView reloadData];
        }else{
            [[[iToast makeText:@"评论失败"]setGravity:iToastGravityCenter] show];
        }
        
    } failure:^(NSError *error) {
        
    }];
    NSLog(@"user.name = %@",UserModel.username);
    
    NSLog(@"%@",textViewGet.text);
}

#pragma mark 评论
-(void)commentButtonClickindex:(NSIndexPath *)indexPath{
    NSLog(@"评论---");
    
    if (self.dataArray) {
        ZCCommentDetailsVC *zcmment = [[ZCCommentDetailsVC alloc]init];
        zcmment.comments = self.dataArray[indexPath.row-1];
        zcmment.isarticles = 1;
        zcmment.pid = self.urlID;
        zcmment.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:zcmment animated:YES];
    }
}

#pragma mark 赞
-(void)likeButtonClickindex:(NSIndexPath *)indexPath islogin:(BOOL)login{
    NSLog(@"赞");
    if (login== YES) {
        ZCInvolvedDetailsModelHotComments *model = self.dataArray[indexPath.row-1];
        [NetworkManager requestFoundingGetOnecommentlikeWithCId:model.hotCommentsIdentifier Mid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
        } failure:^(NSError *error) {
            
        }];
    }else{
        [self login];
    }
}

#pragma mark 登录
-(void)login{
    ZCLoginVC *loginVC = [[ZCLoginVC alloc]init];
    loginVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:loginVC animated:YES];
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.sectionFooterHeight = 0.001;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.hidden = YES;
    }
    return _tableView;
}

- (UIWebView *)webView
{
    if (!_webView) {
        UIWebView *web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        web.delegate = self;
        web.scrollView.bounces = NO;
        web.scrollView.scrollEnabled = NO;
        _webView = web;
    }
    return _webView;
}


@end
